package com.yehongyu.mytools.log;

import java.util.Enumeration;

import org.apache.log4j.Appender;
import org.apache.log4j.AsyncAppender;
import org.apache.log4j.FileAppender;
import org.apache.log4j.Logger;
import org.apache.log4j.xml.DOMConfigurator;

public class LoggerInit {
	/** 日志记录 */
//	private final Logger logger = Logger.getLogger(getClass());
	private final static Logger logger = Logger.getLogger(LoggerInit.class);
	
	public static void main(String[] args){
		System.out.print(LoggerInit.class);
	}

	static {
		try { // 不能因为该类初始化失败导致其引用类初始化失败
			initProjectLog();
		} catch (Exception e) {
			logger.error("初始化是发生异常",e);
//			e.printStackTrace();
		}
	}

	private static void initProjectLog() {
		// 使log4j配置生效(Logger, Appender)
		DOMConfigurator.configure(LoggerInit.class.getClassLoader().getResource("log4j.xml"));
		Logger loggerLog4jImpl = Logger.getRootLogger();
		// 创建异步Appender来替代FileAppender。
		FileAppender fileAppender = getFileAppender(loggerLog4jImpl);
		fileAppender.activateOptions(); // 很重要，否则原有日志内容会被清空
		AsyncAppender asynAppender = new AsyncAppender();
		asynAppender.addAppender(fileAppender);
		loggerLog4jImpl.addAppender(asynAppender);
		loggerLog4jImpl.removeAppender(fileAppender);
		logger.info("成功为PROJECT LOGGER添加Appender. 输出路径:" + fileAppender.getFile());
	}

	private static FileAppender getFileAppender(Logger logger) {
		FileAppender fileAppender = null;
		for (Enumeration<?> appenders = logger.getAllAppenders(); (null == fileAppender)
				&& appenders.hasMoreElements();) {
			Appender appender = (Appender) appenders.nextElement();
			if (FileAppender.class.isInstance(appender)) {
				fileAppender = (FileAppender) appender;
			}
		}
		return fileAppender;
	}

}
